package cn.eng.pet.service.impl;

import cn.eng.basic.exception.BusinessException;
import cn.eng.basic.service.IBaiduAiAuditService;
import cn.eng.basic.service.impl.BaiduAiAuditServiceImpl;
import cn.eng.basic.util.*;
import cn.eng.order.domain.OrderPetAcquisition;
import cn.eng.order.mapper.OrderPetAcquisitionMapper;
import cn.eng.org.domain.Employee;
import cn.eng.org.domain.Shop;
import cn.eng.org.mapper.EmployeeMapper;
import cn.eng.org.mapper.ShopMapper;
import cn.eng.pet.domain.SearchMasterMsg;
import cn.eng.pet.domain.SearchMasterMsgAuditLog;
import cn.eng.pet.dto.OrderDto;
import cn.eng.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.eng.pet.mapper.SearchMasterMsgMapper;
import cn.eng.pet.query.SearchMasterMsgQuery;
import cn.eng.pet.service.ISearchMasterMsgService;
import cn.eng.basic.service.impl.BaseServiceImpl;
import cn.eng.user.domain.Logininfo;
import cn.eng.user.domain.User;
import cn.eng.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 业务实现类：
 */
@Service
@Transactional
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {
    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    /**
     * 发布寻主消息的业务
     *
     * @param searchMasterMsg
     * @param request
     * @return
     */
    @Override
    public AjaxResult publish(SearchMasterMsg searchMasterMsg, HttpServletRequest request) {
        // name: '小七',
        // price: 10,
        // age: 3,
        // gender: 1,
        // coatColor: '黑色',
        // resources: null,
        // petType: 1,
        // address: null,
        // title: '小七寻主'
        // UserId -发布人 - request获取
        // shopId - 分配给哪一个店铺，审核通过之后再分配 - 现在不用管
        // note - 发布寻主消息的说明 - 不用管

        //一:保存寻主信息
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        searchMasterMsg.setUserId(user.getId());
        searchMasterMsgMapper.save(searchMasterMsg);//添加之后 有自增id
        //二：智能审核
        Boolean boo1 = baiduAiAuditService.textAudit(searchMasterMsg.getName() + searchMasterMsg.getTitle());
        Boolean boo2 = baiduAiAuditService.imageAudit(searchMasterMsg.getResources());
        if (boo1 && boo2) {//都通过
            //三：审核通过：1.改state=1 2.分配最近50公里以内的店铺 3.记录审核日志 4.发短信或邮箱告诉店铺管理员去接回宠物
            //1.改state=1
            searchMasterMsg.setState(1);
            //2.分配最近的50公里以内的店铺
            List<Shop> shops = shopMapper.loadAll();//获取所有的店铺
            Point point = DistanceUtils.getPoint(searchMasterMsg.getAddress());//获取地址并解析地址
            Shop nearestShop = DistanceUtils.getNearestShop(point, shops);
            if (nearestShop == null) {//如果50公里以内没有店铺=>到寻主池
                searchMasterMsg.setState(3);
            } else {
                searchMasterMsg.setShopId(nearestShop.getId());
                //4.发送短信 或者邮箱告诉店铺管理员去接回宠物
                Employee employee = employeeMapper.loadById(nearestShop.getAdminId());
                //SmsUtils.sendSms(employee.getPhone(),"你有新的订单，请在3天之内去【"+searchMasterMsg.getAddress()+"】接回宠物");
                System.out.println("你有新的订单，请在3天之内去【" + searchMasterMsg.getAddress() + "】接回宠物");
            }
            searchMasterMsgMapper.update(searchMasterMsg);
            //3.记录审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(searchMasterMsg.getId());
            log.setState(1);
            //智能审核 没有审核人
            log.setNote("审核成功");
            searchMasterMsgAuditLogMapper.save(log);
            return new AjaxResult();
        } else {
            //四：审核失败: 1.改状态state=-1 2.记录审核日志 3.发短信或邮箱告诉用户重新修改资料再分布
            //1.设置状态 为-1
            searchMasterMsg.setState(-1);
            searchMasterMsgMapper.update(searchMasterMsg);
            //2.记录审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(searchMasterMsg.getId());
            log.setState(0);
            //智能审核，没有审核人
            //智能审核 没有审核人
            log.setNote("审核失败");
            searchMasterMsgAuditLogMapper.save(log);
            //发送邮箱告诉用户审核失败 重新修改寻主消息
            //SmsUtils.sendSms("user.getPhone(),"你的消息审核失败，请重新修改之后再发布"");
            System.out.println("你的消息审核失败，请重新修改之后再发布");
            return new AjaxResult(false, "寻主消息审核失败");
        }

    }

    /**
     * 用户查询所有寻主消息
     *
     * @param query
     * @param request
     * @return
     */
    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, HttpServletRequest request) {
        //获取登录人的信息
        Logininfo logininfo = LoginContext.getLogininfo(request);
        //通过logininfoId查询user对象
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        //把用户对象的id设置到查询里面
        query.setUserId(user.getId());
        //使用super调用 同时返回
        return super.queryPage(query);
    }

    /**
     * 管理员查询待处理寻主消息
     *
     * @param query
     * @param request
     * @return
     */
    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(1);//待处理

        //区分平台管理员或店铺管理员
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.loadByLogininfoId(logininfo.getId());
        if(employee.getShop_id() != null){//店铺管理员
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }
        /**
         * 管理员查询已完成寻主消息
         * @param query
         * @param request
         * @return
         */
        @Override
        public PageList<SearchMasterMsg> finish(SearchMasterMsgQuery query, HttpServletRequest request){
            query.setState(2);
            return super.queryPage(query);
        }

        /**
         * 管理员查询寻主池寻主消息
         * @param query
         * @param request
         * @return
         */
        //平台管理员或店铺管理员都可以看：寻主池中的消息shopId is null。只要是state=3，shopId就是null
        @Override
        public PageList<SearchMasterMsg> toSearchMasterPool(SearchMasterMsgQuery query, HttpServletRequest request){
            query.setState(3);
            return super.queryPage(query);
        }

    /**
     * 拒单
     * @param id
     */
    @Override
    public void reject(Long id) {
        searchMasterMsgMapper.reject(id);
    }

    /**
     * 接单
     * @param orderDto
     */
    @Override
    public void accept(OrderDto orderDto) {
        //一.判断当前订单是否正在处理- 根据寻主消息的id查询 再判断
        OrderPetAcquisition dborder = orderPetAcquisitionMapper.loadByMsgId(orderDto.getMsgId());
        if (dborder!=null){
            throw new BusinessException("正在处理,请勿重复接单");
        }
        //二：生成收购订单
        SearchMasterMsg msg = searchMasterMsgMapper.loadById(orderDto.getMsgId());//查询寻主消息
        OrderPetAcquisition order = orderDto2Order(orderDto,msg);
        orderPetAcquisitionMapper.save(order);
        //三：通知接单人 - 发短信
        //Employee employee = employeeMapper.loadById(orderDto.getHandler());//通过处理人的id, 获取处理人的信息
        //SmsUtils.sendSms(employee.getPhone(),"你有新的订单，请在3天内去"+order.getAddress()+"接回宠物");
        System.out.println("你有新的订单，请在3天内去"+order.getAddress()+"接回宠物");
    }

    private OrderPetAcquisition orderDto2Order(OrderDto orderDto, SearchMasterMsg msg) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        String orderSn = CodeGenerateUtils.generateOrderSn(msg.getUserId());
        order.setOrderSn(orderSn);
        order.setDigest(orderDto.getNote());
        //三天后没有接单就自动取消---定时器
        order.setLastcomfirmtime(new Date(System.currentTimeMillis()+3*24*60*60*1000));
        order.setPrice(msg.getPrice());
        //支付类型 和宠物id 需要接收后确认订单之后再设置
        order.setUserId(msg.getUserId());
        order.setShopId(msg.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(orderDto.getHandler());
        order.setSearchMasterMsgId(orderDto.getMsgId());
        return order;
    }
}


